/**
 * Created by csy on 2018/1/10
 */
var validateWapper;
require(['jquery', 'libs/alert', 'layout/util', 'libs/bootstrap3-typeahead', 'js-path/jquery-validation-wrapper'], function ($, $alert) {
    judge();
    formValideInit();
    $('#back').on('click', function () {
       // window.history.go(-1);
        window.location.href = 'service-list';
    });
    $('#submit_form').on('click', function () {
        $('#main_form').submit();
    });
    //客户名称
    $('#main_form input[name=entName]').typeahead({
        source: function (query, process) {
            $.get("api/v1/p/crm/enterpriseInfo/list",
                {
                    name: query,
                    page: 1, rows: 999
                },
                function (result) {
                    if (result.code == 200) {
                        var data = [];
                        if (result.data.rows) {
                            $.each(result.data.rows, function (index, obj) {
                                data.push(JSON.stringify(obj));
                            });
                        }
                        process(data);
                    } else {
                        $alert(result.message);
                    }
                });
        },
        items: 9999,
        matcher: function (item) {
            return true;
        },
        highlighter: function (item) {
            var obj = JSON.parse(item);
            return obj.name;
        },
        updater: function (item) {
            var obj = JSON.parse(item);
            $('#entId').val(obj.id);
            selectInit($("#main_form select[name=billAccountId]"), 'api/v1/p/crm/enterpriseInfo/load', {id: obj.id});
            return obj.name;
        }
    });

    $('#main_form select[name=warehouseCode]').on('change',function () {
        var currency = $(this).find('option:checked').data('currency');
        $('#main_form input[name=currency]').val(currency);
    });
});
function selectInit($select, url, data, value) {
    $.ajax({
        url: url,
        type: 'get',
        data: data,
        dataType: 'json',
        success: function (result) {
            if (result.code == 200) {
                if (!(result.data || result.data.length > 0)) {
                    var span = '<span  class="error-info"><span class="glyphicon glyphicon-remove">' +
                        '</span>未找到相关数据</span>';
                    $select.parent('div').next('div.col-xs-3').empty().append(span);
                }
                $select.text('');
                $select.append("<option value=''>请选择</option>");
                if(result.data.billingAccounts){
                    $.each(result.data.billingAccounts, function (index, obj) {
                        $select.append("<option value='" + obj.id + "' data-currency='"+obj.currency+"'>" + obj.accountName + "</option>");
                        if(obj.defaultAccount=='Y'){
                            value = obj.id;
                           // $('#main_form input[name=currency]').val(obj.currency);
                        }
                    });
                }else {
                    $.each(result.data, function (index, obj) {
                        if (obj.warehouseCode) {
                            $select.append("<option value='" + obj.warehouseCode + "' data-currency='"+obj.currency+"'>" + obj.warehouseName + "</option>");
                        }else {
                            $select.append("<option value='" + obj.id + "'>" + obj.name + "</option>");
                        }
                    });
                }
                $select.val(value);
            } else {
                var span = '<span class="error">' + result.message + '</span>';
                $select.parents('.error-wrap').find(".error-txt").empty().append(span);
            }
        }
    })
}
//judge判断新增或更新
function judge() {
    var url = window.location.href;
    if (url.indexOf("id=") > 0) {
        $('#main_form').attr('action', 'api/v1/p/mms/service/order/consume/update');
        $('span.name:first').html('修改扣费服务');
        var id = $.getUrlParam('id');
        load(id);
    } else {
        selectInit($("#main_form select[name=warehouseCode]"), 'api/v1/p/crm/warehouse/query', {warehouseType: 'A'});
    }
}

//load
function load(id) {
    $.ajax({
        url: 'api/v1/p/mms/service/order/consume/detail',
        type: 'post',
        data: {
            id: id
        },
        dataType: 'json',
        success: function (result) {
            if (result.code == 200) {
                $('#main_form').setForm(result.data);
                selectInit($("#main_form select[name=warehouseCode]"), 'api/v1/p/crm/warehouse/query', {warehouseType: 'A'},
                    result.data.warehouseCode);
                selectInit($("#main_form select[name=billAccountId]"), 'api/v1/p/crm/enterpriseInfo/load', {id: result.data.entId},
                    result.data.billAccountId);
            } else {
                $alert(result.message);
            }
        },
        error: function (e) {
            console.error('api/v1/p/mms/service/order/consume/detail 接口调用失败 ')
        }
    })
}
//表单验证
function formValideInit() {
    validateWapper = $('#main_form').validateWapper({
        rules: {
            warehouseCode: {required: true},
            entId: {required: true},
            billAccountId: {required: true},
            amount: {required: true, number: true, min: 0.01},
            factAmount: {required: true, number: true, min: 0.01},
            consumeReasonContent: {maxlength: 200}
        }, submitHandler: function () {
            var formData = $('#main_form').serializeObject();
            $.ajax({
                url: $('#main_form').attr('action'),
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json;charset=utf-8'
            })
                .done(function (res) {
                    if (res.code == 200) {
                        window.location.href = 'service-list';
                    } else {
                        $alert(res.message);
                    }
                });
        }
    });
}